<template>
  <a-card :bordered="false" :style="{ height: '100%' }">
    <a-row :gutter="24">
      <a-col :md="4">
        <a-list item-layout="vertical" :data-source="roles">
          <a-list-item slot="renderItem" :key="index" slot-scope="item, index">
            <a-list-item-meta :style="{ marginBottom: '0' }">
              <span slot="description" style="text-align: center; display: block">{{ item.description }}</span>
              <a slot="title" style="text-align: center; display: block" @click="edit(item)">{{ item.name }}</a>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
      </a-col>
      <a-col :md="20">
        <div style="max-width: 800px">
          <a-divider v-if="isMobile()" />
          <div v-if="mdl.id">
            <h3>角色：{{ mdl.name }}</h3>
          </div>
          <a-form :form="form" :layout="isMobile() ? 'vertical' : 'horizontal'">
            <a-form-item label="唯一键">
              <a-input v-decorator="[ 'id', {rules: [{ required: true, message: 'Please input unique key!' }]} ]" placeholder="请填写唯一键" disabled />
            </a-form-item>

            <a-form-item label="角色名称">
              <a-input v-decorator="[ 'name', {rules: [{ required: true, message: 'Please input role name!' }]} ]" placeholder="请填写角色名称" />
            </a-form-item>

            <a-form-item label="状态">
              <a-select v-decorator="[ 'status', {rules: []} ]">
                <a-select-option :value="true">正常</a-select-option>
                <a-select-option :value="false">禁用</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="备注说明">
              <a-textarea v-decorator="[ 'description', {rules: [{ required: true, message: 'Please input role name!' }]} ]" :row="3" placeholder="请填写角色描述" />
            </a-form-item>

            <a-form-item label="拥有权限">
              <a-row v-for="(permission, index) in permissions" :key="index" :gutter="16">
                <a-col :xl="4" :lg="24">
                  {{ permission.domain.name }}：
                </a-col>
                <a-col :xl="20" :lg="24">
                  <a-checkbox
                    v-if="permission.actionsOptions.length > 0"
                    :indeterminate="permission.indeterminate"
                    :checked="permission.checkedAll"
                    @change="onChangeCheckAll($event, permission)"
                  >
                    全选
                  </a-checkbox>
                  <a-checkbox-group v-model="permission.selected" :options="permission.actionsOptions" @change="onChangeCheck(permission,true)" />
                </a-col>
              </a-row>
            </a-form-item>

          </a-form>
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import pick from 'lodash.pick'

export default {
  name: 'RoleList',
  layout: 'basic-layout',
  components: {},
  mixins: [mixinDevice],
  data () {
    return {
      form: this.$form.createForm(this),
      mdl: {},

      roles: [],
      permissions: []
    }
  },
  created () {
    if (process.client) {
      return this.$authApi.getRoles()
        .then(res => {
          res.data.forEach(item => {
            console.log(item)
            item.role.permissions = item.permissions
            this.roles.push(item.role)
          })
          console.log('this.roles', this.roles)
          this.loadPermissions()
        })
    }
  },
  methods: {
    callback (val) {
      console.log(val)
    },

    add () {
      this.edit({ id: 0 })
    },

    edit (record) {
      this.roles = []
      this.$authApi.getRoles()
        .then(res => {
          res.data.forEach(item => {
            item.role.permissions = item.permissions
            this.roles.push(item.role)
            this.roles.forEach(role => {
              if (role.id === record.id) {
                record = role
                this.mdl = Object.assign({}, record)
                // 有权限表，处理勾选
                if (this.mdl.permissions && this.permissions) {
                  // 先处理要勾选的权限结构
                  const permissionsAction = {}
                  this.mdl.permissions.forEach(permission => {
                    permissionsAction[permission.id] = true
                  })

                  console.log('permissionsAction', permissionsAction)
                  // 把权限表遍历一遍，设定要勾选的权限 action
                  this.permissions.forEach(permission => {
                    const selected = []
                    permission.permissions.forEach(item => {
                      if (permissionsAction[item.id] === true) {
                        selected.push(item.id)
                      }
                    })
                    console.log(selected)
                    permission.selected = selected || []
                    this.onChangeCheck(permission, false)
                  })
                  console.log('this.permissions', this.permissions)
                }

                this.$nextTick(() => {
                  this.form.setFieldsValue(pick(this.mdl, 'id', 'name', 'status', 'description'))
                })
                console.log('this.mdl', this.mdl)
              }
            })
          })
        })
    },

    onChangeCheck (permission, net) {
      console.log(permission)
      const add = permission.selected.filter(key => !permission.prevSelected.includes(key))[0]
      const del = permission.prevSelected.filter(key => !permission.selected.includes(key))[0]
      permission.indeterminate = !!permission.selected.length && (permission.selected.length < permission.actionsOptions.length)
      permission.checkedAll = permission.selected.length === permission.actionsOptions.length
      if (net) {
        if (add) {
          this.$resourceApi.addRRR(this.mdl.id, add).then(res => {
            permission.prevSelected = permission.selected
          })
        } else {
          this.$resourceApi.delRRR(this.mdl.id, del).then(res => {
            permission.prevSelected = permission.selected
          })
        }
      }
    },
    onChangeCheckAll (e, permission) {
      console.log(permission)
      if (!permission.checkedAll) {
        this.$resourceApi.addRRRs(this.mdl.id, permission.domain.id).then(res => {
          Object.assign(permission, {
            selected: e.target.checked ? permission.actionsOptions.map(obj => obj.value) : [],
            indeterminate: false,
            checkedAll: e.target.checked
          })
        })
      } else {
        this.$resourceApi.delRRRs(this.mdl.id, permission.domain.id).then(res => {
          Object.assign(permission, {
            selected: e.target.checked ? permission.actionsOptions.map(obj => obj.value) : [],
            indeterminate: false,
            checkedAll: e.target.checked
          })
        })
      }
    },
    async loadPermissions () {
      await this.$resourceApi.getAllPermission().then(res => {
        const result = res.data
        this.permissions = result.map(permission => {
          const options = permission.permissions
          permission.checkedAll = false
          permission.selected = []
          permission.indeterminate = false
          permission.actionsOptions = options.map(option => {
            return {
              label: option.name,
              value: option.id
            }
          })
          permission.prevSelected = permission.selected
          return permission
        })
      })
      this.edit(this.roles[0])
    }
  }
}
</script>

<style scoped>

</style>
